<?php
namespace control;
/*
*不良原因分析类
*/

class badAnalysisClass extends adIndexClass
{
    private const page = 'badAnalysis';
    private const title = '不良原因分析';
    private const table = 'quality_order';
    private const tableMx = 'quality_order_reason';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'          => [
                        'name'  => "类型",
                        'width' => 300,
                    ],
                    'reason'          => [
                        'name'  => "不良原因",
                        'width' => 300,
                    ],
                    'level'          => [
                        'name'  => '不良等级',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'num'          => [
                        'name'  => '送检数量',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'badNum'          => [
                        'name'  => '不良数量',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'badRate'          => [
                        'name'  => '不良占比',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "不良原因" => text(array("name" => "reason")),
                    "类型" => select(["name" => "type",'option'=>['1'=>'来料检验','2'=>'制终检验','3'=>'发货检验']]),
                    "不良等级" => text(array("name" => "level")),
                ],
                [
                    "日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        $button .= "<span class='spanButton' onclick=\"layer('badAnalysis','statistics',{})\">帕累托图</span>\n";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "c.reason" => $this->post('reason'),
        );
        //全等查询数组
        $equal = array(
            "a.type" => $this->post('type'),
            "c.level" => $this->post('level'),
            "a.coid"=>self::$coid,
            "a.state"=>'已质检',
        );
        $and ='';
        if ($this->post('createTime')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'), 'date', 'a.checkTime');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'type',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = $totalWhere = search(array("like" => $like, "=" => $equal)) . $and;
        $where .= " group by a.type,b.reasonId";
        $page = $this->page(array(
            "table" => self::table." as a join ".self::tableMx." as b on b.orderId = a.id join quarantine_reason as c on c.id = b.reasonId",
            'field'=>"any_value(sum(a.num)) as num,a.type as type,ifnull(sum(any_value(b.num)),0) as badNum,any_value(c.reason) as reason,any_value(c.level) as level",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'type':
                        $type = match ($array['type']){
                            '1'=>'来料检验',
                            '2'=>'制终检验',
                            '3'=>'发货检验',
                            default=>'',
                        };
                        $row[] = $type;
                        break;
                    case 'num':
                    case 'badNum':
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case 'badRate':
                        $row[] = machiningOrderClass::formatRatio($array['badNum'],$array['num']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table." as a join ".self::tableMx." as b on b.orderId = a.id join quarantine_reason as c on c.id = b.reasonId",
            'single' => $totalWhere,
            'field'  => "ifnull(sum(a.num),0) as num,ifnull(sum(b.num),0) as badNum",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'badNum'        => self::lostZero($totalQuery['badNum'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 帕累托图
     */
    public function statistics(): bool|string
    {

        // 搜索文本框
        $searchTxt = self::searchText([
                "name" => "month",
                "title" => "日期",
                "class" => "line28",
                'laydate' => ['type' => 'month', 'range' => '~']
            ]). select(["name" => "orderType",'option'=>['1'=>'来料检验','2'=>'制终检验','3'=>'发货检验'], 'title' => '类型']);

        //工资趋势
        $salaryTrendHtml = $this->paretoChart(['title' => '帕累托图','searchText'=>'', 'fun' => 'salaryTrend']);
        $html =<<<eof
<script src='{$this->root}static/javascript/echarts.min.js'></script>
<div style="padding: 10px">
    <div class="search">$searchTxt<input class="searchSub" type="button" onclick="searchData()" value="查询"></div>
    <div>$salaryTrendHtml</div>
</div>
<script>
$(function (){
    searchData();
})
function searchData() {
    let month = $("[name='month']").val();
    let type = $("[name='orderType']").val();
   $.post(root+'control/adIndex.html?cla=badAnalysis&fun=salaryTrend',{months:month,type:type},function(res) {
      $("#salaryTrendHtml").empty().append(res.html)
   },'json')
}
</script>
eof;

        //返回
        return $this->layer(array("title" => "帕累托图", "height" => 600, "width" => 1100, "html" => $html, "button" => false));
    }

    /**
     * 二维数组按指定key从大到小排序
     * @param $array
     * @param $key
     * @param string $order
     * @return mixed
     */
    function sortByKey($array, $key, $order = 'desc') {
        usort($array, function($a, $b) use ($key, $order) {
            $result = $a[$key] - $b[$key];
            if ($order === 'desc') {
                return -$result;
            } else {
                return $result;
            }
        });
        return $array;
    }
    /**
     *
     */
    public function salaryTrend(): bool|string
    {
        $and = '';
        if ($this->post('months')){
            $and .= self::timeComparison($this->post('months'), 'date', 'a.checkTime');
        }
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
            "a.type" => $this->post('type'),
            "a.coid"=>self::$coid,
            "a.state"=>'已质检',
        );
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $all = find(array("table" => self::table." as a join ".self::tableMx." as b on b.orderId = a.id join quarantine_reason as c on c.id = b.reasonId",
            'field'=>"any_value(sum(a.num)) as num,ifnull(sum(any_value(b.num)),0) as badNum,a.type as type,any_value(c.reason) as reason", "where" => $where." group by a.type,b.reasonId"));
        $xData   = [];
        $yData   = [];
        $perData = [];
        $all['array'] = self::sortByKey($all['array'],'badNum');
        foreach ($all['array'] as $array) {
            $xData[]  = $array['reason'];
            $yData[] = self::lostZero($array['badNum'],'numPrecision');
            $perData[] = $array['num']>0?(machiningOrderClass::formatRatio($array['badNum'],$array['num'],4,false)):0;
        }
        $xData = json_encode($xData,320);
        $yData = json_encode($yData,320);
        $perData = json_encode($perData,320);
        $option = "
		var option = { tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    
  },
  legend: {
    data: ['不良数', '不良影响度']
  },
  xAxis: [
    {
      type: 'category',
      data: {$xData},
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '不良数',
      axisLabel: {
        formatter: '{value}'
      }
    },
    {
      type: 'value',
      name: '不良影响度',
      axisLabel: {
        formatter: '{value} %'
      }
    }
  ],
  series: [
    {
      name: '不良数',
      type: 'bar',
      tooltip: {
        valueFormatter: function (value) {
          return value;
        }
      },
      data: {$yData}
    },
    {
      name: '不良影响度',
      type: 'line',
      yAxisIndex: 1,
      tooltip: {
        valueFormatter: function (value) {
          return value + ' %';
        }
      },
      data: {$perData}
    }
  ]
		};";
        $json['html'] = $this->echarts($option);
        return json_encode($json, 320);
    }

    /**
     *
     */
    private function paretoChart(array $data): string
    {
        return <<<EOT
<div id='{$data['fun']}Html' style="height: 460px">数据查询中。。。</div>
EOT;
        //返回
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            $sql   = $_SESSION[self::page]['sql'];
            $result   = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $type = match ($array['type']){
                    '1'=>'来料检验',
                    '2'=>'制终检验',
                    '3'=>'发货检验',
                    default=>'',
                };
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '类型'=>$type,
                            '不良原因'=>$array['reason'],
                            '不良等级'=>$array['level'],
                            '送检数量'=>self::lostZero($array['num'],'numPrecision'),
                            '不良数量'=>self::lostZero($array['badNum'],'numPrecision'),
                            '不良占比'=>machiningOrderClass::formatRatio($array['badNum'],$array['num']),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了".self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title.".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'类型',
                    'aliasName'=>'类型',
                ],
                [
                    'columnName'=>'不良原因',
                    'aliasName'=>'不良原因',
                ],
                [
                    'columnName'=>'不良等级',
                    'aliasName'=>'不良等级',
                ],
                [
                    'columnName'=>'送检数量',
                    'aliasName'=>'送检数量',
                ],
                [
                    'columnName'=>'不良数量',
                    'aliasName'=>'不良数量',
                ],
                [
                    'columnName'=>'不良占比',
                    'aliasName'=>'不良占比',
                ],
            ]
        };
    }
}

